package com.icarcom.cn;

import butterknife.Bind;
import butterknife.OnClick;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.print_sdk.SerialManager;
import com.google.gson.Gson;
import com.icarcom.cn.api.ACTION;
import com.icarcom.cn.api.HttpCallBack;
import com.icarcom.cn.api.HttpUtils;
import com.icarcom.cn.base.BaseActivity;
import com.icarcom.cn.ui.CaptureActivity;
import com.icarcom.cn.ui.bean.GetCodeBean;
import com.icarcom.cn.ui.bean.MainTypeBean;
import com.icarcom.cn.ui.util.MainTypePopup;
import com.icarcom.cn.util.DesCode;
import com.icarcom.cn.util.GsonUtil;
import com.icarcom.cn.util.L;
import com.icarcom.cn.util.ProgressDialog;
import com.icarcom.cn.util.SP;
import com.icarcom.cn.util.SpContent;
import com.icarcom.cn.util.T;
import com.icarcom.cn.util.ZXingUtilsTest;
import com.icarcom.cn.util.printUtil.ByteUtils;
import com.icarcom.cn.util.printUtil.PrintContract;
import com.lxj.xpopup.XPopup;
import com.lzy.okgo.cache.CacheMode;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

public class MainActivity extends BaseActivity implements HttpCallBack,SerialManager.OnDataReceiveListener {
    public final static int FILECHOOSER_RESULTCODE_ADDRESS_ENT_CODE  = 002;
    @Bind(R.id.et_main_device)
    EditText et_main_device;
    @Bind(R.id.tv_main_type)
    public TextView tv_main_type;
    @Bind(R.id.et_main_money)
    EditText et_main_money;
    @Bind(R.id.tv_login_print_code)
    TextView tv_login_print_code;
    @Bind(R.id.iv_main_score_code)
    ImageView iv_main_score_code;

    public String timestamp = "",signc = "",code = "",print_url = "",device_name = "";
    ArrayList<String> NameList = new ArrayList<>();
    public ArrayList<String> CodeList = new ArrayList<>();

    List<GetCodeBean.RemarkListBean> remarkList = new ArrayList<>();

    public static MainActivity instance = null;
    ProgressDialog progressDialog;

    int number = 1000000001,rechargeMode;
    private SerialManager serialManager;
    public boolean check_paper=true;
    private PrintContract printContract;

    Bitmap codeBmp;

    @Override
    protected int getLayoutId() {
        instance = this;
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        super.initView();
        progressDialog = new ProgressDialog(this);

        serialManager=new SerialManager();
        serialManager.open ();
        serialManager.setOnDataReceiveListener (this);

        printContract=new PrintContract (this, serialManager);
        try {
            Thread.sleep (10);
            printContract.printInit ();
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
        printContract.getVersion ();


        et_main_device.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void afterTextChanged(Editable editable) {
                if(editable.toString().length() == 8){
                    getTypeData();
                }
            }
        });
    }

    /**
     * 获取物管角色类型
     */
    private void getTypeData() {
        progressDialog.loadShow();
        long timeStampSec = System.currentTimeMillis()/1000;
        timestamp = String.format("%010d", timeStampSec);

        SortedMap<String,Object> params = new TreeMap<>();
        params.put("device",et_main_device.getText().toString());
        params.put("timestamp",timestamp);
        params.put("signKey", SpContent.DesKey);

        Gson gsons = new Gson();
        String sourStrs = gsons.toJson(params);
        signc = DesCode.MD5(sourStrs);

        HashMap<String,String> param = new HashMap<>();
        param.put("device",et_main_device.getText().toString());
        param.put("token", SP.get(this,SpContent.userToken,"")+"");
        param.put("timestamp",timestamp);//时间戳，秒数
        param.put("sign",signc);//MD5签名后转为大写
        HttpUtils.doPost(this, ACTION.GETTYPEBYDEVICE, param, CacheMode.REQUEST_FAILED_READ_CACHE, true, this);
    }

    /**
     * 获取二维码
     */
    private void uploadData() {
        progressDialog.loadShow();
        long timeStampSec = System.currentTimeMillis()/1000;
        timestamp = String.format("%010d", timeStampSec);

        SortedMap<String,Object> params = new TreeMap<>();
        params.put("device",et_main_device.getText().toString());
        params.put("code",code);
        params.put("payCharge",et_main_money.getText().toString());
        params.put("timestamp",timestamp);
        params.put("signKey", SpContent.DesKey);

        Gson gsons = new Gson();
        String sourStrs = gsons.toJson(params);
        signc = DesCode.MD5(sourStrs);

        HashMap<String,String> param = new HashMap<>();
        param.put("device",et_main_device.getText().toString());
        param.put("timestamp",timestamp);//时间戳，秒数
        param.put("code",code);
        param.put("payCharge",et_main_money.getText().toString());
        param.put("sign",signc);//MD5签名后转为大写
        HttpUtils.doPost(this, ACTION.GETEWEIMADDATA, param, CacheMode.REQUEST_FAILED_READ_CACHE, true, this);
    }

    @Override
    public void onSuccess(int action, String res) {
        switch (action){
            /**
             * 获取二维码
             */
            case ACTION.GETEWEIMADDATA:
                progressDialog.cancel();
                L.e("????????????获取二维码      "+res);
                GetCodeBean getCodeBean = GsonUtil.toObj(res,GetCodeBean.class);
                if(getCodeBean.getRetCode().equals("000000")){
                    print_url = getCodeBean.getQrCodeUrl();
                    remarkList = getCodeBean.getRemarkList();

                    printGBKText();

                }else{
                    T.show(getCodeBean.getRetMsg());
                }
                break;
            /**
             * 获取类型
             */
            case ACTION.GETTYPEBYDEVICE:
                L.e("?????????????获取类型      "+res);
                progressDialog.cancel();
                MainTypeBean mainTypeBean = GsonUtil.toObj(res,MainTypeBean.class);
                if(mainTypeBean.getRetCode().equals("000000")){
                    int select = 0;

                    NameList.clear();
                    CodeList.clear();
                    for(int i=0;i<mainTypeBean.getModeList().size();i++){
                        NameList.add(mainTypeBean.getModeList().get(i).getName());
                        CodeList.add(mainTypeBean.getModeList().get(i).getCode());
                        if(!mainTypeBean.getModeList().get(i).getSelected().equals("")){
                            select = i;
                        }
                    }

                    tv_main_type.setText(NameList.get(select));
                    code = CodeList.get(select);
                    et_main_money.setText(mainTypeBean.getPayCharge());
                }else{
                    T.show(mainTypeBean.getRetMsg());
                }
                break;
        }
    }

    @OnClick({R.id.tv_main_score,R.id.li_main_type,R.id.tv_main_type,R.id.tv_login_submit,R.id.tv_login_print_code})
    public void onClick(View view){
        switch (view.getId()){
            /**
             * 点击扫码
             */
            case R.id.tv_main_score:
                startActivityForResult(new Intent(this, CaptureActivity.class),FILECHOOSER_RESULTCODE_ADDRESS_ENT_CODE);
                break;
            /**
             * 获取物管角色类型
             */
            case R.id.tv_main_type:
            case R.id.li_main_type:
                if(et_main_device.getText().toString().length() != 8){
                    T.show("请扫描或输入8位设备号");
                }else{
                    new XPopup.Builder(MainActivity.this)
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                            .asCustom(new MainTypePopup(MainActivity.this, new MainTypePopup.ShopDeatilListener() {
                                @Override
                                public void onClick(View view) {
                                }
                            },NameList))
                            .show();
                }
                break;
            /**
             * 点击生成二维码
             */
            case R.id.tv_login_submit:
                if(et_main_device.getText().toString().length() != 8){
                    T.show("请扫描或输入8位设备号");
                }else if(tv_main_type.getText().toString().equals("")){
                    T.show("请选择物管角色类型");
                }else if(et_main_money.getText().toString().equals("")){
                    T.show("请输入激活金额");
                }else{
                    uploadData();
                }
                break;
            /**
             * 点击打印二维码
             */
            case R.id.tv_login_print_code:

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FILECHOOSER_RESULTCODE_ADDRESS_ENT_CODE:
                String label_str = data.getStringExtra("change");

                if(label_str.equals("yes")){
                    String number = data.getStringExtra("score");
                    et_main_device.setText(number);
                }
                break;
        }
    }

    @Override
    public void showLoadingDialog() {

    }

    @Override
    public void showErrorMessage(String s) {

    }

    private void printGBKText() {
        printPicText(GetPrintStr(),print_url);
    }

    public String GetPrintStr() {

        StringBuilder sb = new StringBuilder();

        for(int i=0;i<remarkList.size();i++) {
            sb.append(remarkList.get(i).getName()+"："+remarkList.get(i).getValue() + "\n");
        }

        return sb.toString();
    }

    public void printPicText(String content,String url){
        printContract.printQRText(number,content,url);
    }

    public Handler handler=new Handler () {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage (msg);
            switch (msg.what) {
                case 101:
                    String version=(String) msg.obj;
                    //tv_version.setText (version);
                    L.e("????    "+version);
                    break;
                case 102:
                    T.show("缺纸");
                    break;
                case 103:
                    T.show("打印失败");
                    break;
                case 104:
                    number+=1; // 流水号自加1 Serial number plus 1
                    T.show("打印成功");
                    break;
            }
        }
    };

    @Override
    public void onDataReceive(byte[] buffer, int size) {
        try {
            if (buffer[0] == 0x39) {
                final String version=new String (buffer, 0, buffer.length, "ISO-8859-1");
                Message message=new Message ();
                message.what=101;
                message.obj=version;
                handler.sendMessage (message);
            } else if (buffer[2] == 0x0C) {
                check_paper=false;
                Message message=new Message ();
                message.what=102;
                handler.sendMessage (message);
            } else if (buffer[1] == 0x40) {
                check_paper=false;
                Message message=new Message ();
                message.what=103;
                handler.sendMessage (message);
            } else if (size == 7) {
                Message message=new Message ();
                message.what=104;
                handler.sendMessage (message);
            } else if (buffer[0] == 0x70) {
                String ret=new String (buffer, 0, buffer.length, "ISO-8859-1");
                Message message=new Message ();
                message.what=105;
                message.obj=ret;
                handler.sendMessage (message);
            } else {
                String hex= ByteUtils.Bytes2HexString (buffer);
                Message message=new Message ();
                message.what=106;
                message.obj=hex;
                handler.sendMessage (message);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace ();
        }
    }
}
